package com.crm.service.impl.contractManager;

import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.dao.mapper.contractManager.CustomerContractMapper;
import com.crm.dao.mapper.customMapper.customerContractCustomMapper.CustomerContractCustomMapper;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.contractManager.CustomerContractExample;
import com.crm.model.entity.contractManager.RepaymentAbility;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.contractManager.CustomerContractQO;
import com.crm.model.qo.customerManager.AnalyseCustomerQO;
import com.crm.model.vo.csd.customerManager.ContractDetailVO;
import com.crm.model.vo.customerContractManager.*;
import com.crm.model.vo.datasearch.DataSearchResultVO;
import com.crm.service.contractManager.CustomerContractDbService;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author yincuimei
 * @Date 2021/3/12 9:59
 * 合同管理
 */
@Service
public class CustomerContractDbServiceImpl implements CustomerContractDbService {
    //合同管理--自动生成mapper
    @Autowired
    private CustomerContractMapper customerContractMapper;

    //合同管理--自定义mapper
    @Autowired
    private CustomerContractCustomMapper contractCustomMapper;

    /**
     * (超级管理员、普通管理员、普通用户)合同管理--合同列表
     * @param customerContractQO ---合同列表查询条件
     * @param orderStr           ---合同列表排序
     * @param accountId          ---当前登录人账号ID(查询个人数据时)
     * @param companyId          ---当前登录人所属公司ID(普通管理员查询本公司数据时)
     * @author yincuimei
     * @return
     */
    @Override
    public List<CustomerContractVO> selectCustomerContractVOList(CustomerContractQO customerContractQO,Integer dateUnit, String orderStr,String accountId,String companyId) {
        return contractCustomMapper.selectCustomerContractVOList(customerContractQO,dateUnit,orderStr,accountId,companyId);
    }

    /**
     * (用户系统)合同管理--合同列表
     * @param customerContractQO   ---查询条件
     * @param dateUnit             ---全部、上月、本周、本月、本年查询条件
     * @param orderStr             ---排序
     * @param accountId            ---当前登录人账号ID
     * @return
     */
    @Override
    public List<CustomerContractVO> selectUserCustomerContractVOList(CustomerContractQO customerContractQO, Integer dateUnit, String orderStr, String accountId) {
        return contractCustomMapper.selectUserCustomerContractVOList(customerContractQO,dateUnit,orderStr,accountId);
    }

    /**
     * 合同列表--查看(根据合同ID查询合同详情)
     * @param contractId  ---合同ID
     * @author yincuimei
     * @return
     */
    @Override
    public CustomerContractDetailVO selectCustomerContractVODetail(String contractId) {
        return contractCustomMapper.selectCustomerContractVODetail(contractId);
    }

    /**
     * 合同作废时后端校验合同状态及回款状态
     * @param contractId  --合同ID
     * @return
     */
    @Override
    public Map selectContractAndPaymentStatus(String contractId) {
        return contractCustomMapper.selectContractAndPaymentStatus(contractId);
    }

    /**
     * 合同列表--修改合同状态
     * @param contractId     ---合同ID
     * @param contractStatus ---合同状态
     * @author yincuimei
     * @return
     */
    @Override
    public Boolean updateContractStatusById(String contractId,String contractStatus) {
        UserAccount userAccount = (UserAccount)SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        CustomerContract customerContract = new CustomerContract();
        customerContract.setContractId(contractId);//合同ID
        customerContract.setContractStatus(contractStatus);//合同状态:1-未生效；2-生效中；3-已结束；4-已作废；5-意外终止；6-挂起
        customerContract.setUpdateTm(new Date());//更新时间
        customerContract.setUpdatePeopleId(userAccount.getAccountId());//更新人ID
        return customerContractMapper.updateByPrimaryKeySelective(customerContract) > 0;
    }

    /**
     * 合同详情(用户系统)--上传补充材料
     * @param customerContract ---合同信息
     * @author yincuimei
     * @return
     */
    @Override
    public Boolean updateContractReplenishAnnex(CustomerContract customerContract) {
        return customerContractMapper.updateByPrimaryKeySelective(customerContract) > 0;
    }

    /**
     * 通过客户id查询合同列表
     * @param customerId 客户id
     * @author luojie
     * @return
     */
    @Override
    public List<CustomerContract> selectContractListByCustomerId(String customerId,String accountId) {
        CustomerContractExample customerContractExample = new CustomerContractExample();
        customerContractExample.setOrderByClause("create_tm desc");
        CustomerContractExample.Criteria criteria = customerContractExample.createCriteria();
        criteria.andCustomerIdEqualTo(customerId);
        criteria.andCreatePeopleIdEqualTo(accountId);
        criteria.andDeleteStatusEqualTo(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        List<CustomerContract> customerContractList = customerContractMapper.selectByExample(customerContractExample);
        return customerContractList;
    }

    /**
     * 新增合同
     * @param customerContract  合同对象
     * @author luojie
     * @return
     */
    @Override
    public Boolean insertCustomerContract(CustomerContract customerContract) {
        int num = customerContractMapper.insertSelective(customerContract);
        return num > 0;
    }

    /**
     * 根据合同主键更细合同基本信息
     * @param customerContract 合同对象
     * @author luojie
     * @return
     */
    @Override
    public Boolean updateCustomerContract(CustomerContract customerContract) {
        int num = customerContractMapper.updateByPrimaryKeySelective(customerContract);
        return num>0;
    }

    /**
     * 联系人详情-订单合同-通过联系人id
     * @param contactId 联系人id
     * @param contractNumber 合同编号
     * @param order 分组类型
     * @return
     */
    @Override
    public List<ContactDetailByCustomerContractVO> selectCustomerContractByContactId(String contactId, String contractNumber, String order) {
        return contractCustomMapper.selectCustomerContractByContactId(contactId,contractNumber,order);
    }

    /**
     * 更新合同审核状态
     * @param contractId
     * @param contractReviewStatus
     * @return
     */
    @Override
    public Boolean updateContractReviewStatus(String contractId, String contractReviewStatus,String accountId,String userName,String contractReviewNotes, Date newDate) {
        CustomerContract customerContract = new CustomerContract();
        customerContract.setContractId(contractId);
        customerContract.setContractReviewStatus(contractReviewStatus);
        customerContract.setReviewerId(accountId);
        customerContract.setReviewerName(userName);
        customerContract.setContractReviewNotes(contractReviewNotes);
        customerContract.setReviewTime(newDate);
        //如果合同审核状态是审核失败，更新合同表为已作废
        if("3".equals(contractReviewStatus)){
            customerContract.setContractStatus("4");
        }
        int num = customerContractMapper.updateByPrimaryKeySelective(customerContract);
        return num>0;
    }

    /**
     * 查询新单会员数量
     * @param qo
     * @return
     */
    @Override
    public List<Long> selectNewVipCount(AnalyseCustomerQO qo) {
        return contractCustomMapper.selectNewVipCount(qo);
    }

    /**
     * 查询续费会员合同
     * @param qo
     * @return
     */
    @Override
    public List<Long> selectRenewalVipCount(AnalyseCustomerQO qo) {
        return contractCustomMapper.selectRenewalVipCount(qo);
    }

    /**
     * 会员合同数量
     * @return
     */
    @Override
    public BigDecimal selectMackAddVipCount(AnalyseCustomerQO qo) {
        return contractCustomMapper.selectMackAddVipCount(qo);
    }

    /**
     * 续费合同数量
     * @param qo
     * @return
     */
    @Override
    public BigDecimal selectRenewalVip(AnalyseCustomerQO qo) {
        return contractCustomMapper.selectRenewalVip(qo);
    }

    /**
     * 会员订单总数量
     * @param qo
     * @return
     */
    @Override
    public Long selectMakeVipCount(AnalyseCustomerQO qo) {
        return contractCustomMapper.selectMakeVipCount(qo);
    }

    /**
     * 计算客户转换排名
     * @param qo
     * @return
     */
    @Override
    public Long selectCustomerSwitchNum(AnalyseCustomerQO qo) {
        return contractCustomMapper.selectCustomerSwitchNum(qo);
    }

    /**
     * 计算会员拥有排名
     * @param qo
     * @return
     */
    @Override
    public Long selectVipOwnNum(AnalyseCustomerQO qo) {
        return contractCustomMapper.selectVipOwnNum(qo);
    }

    /***
     * @Description:根据合同id查询合同信息
     * @Param: contractId
     * @Author: luojie
     * @Date: 2021/4/19 8:40
     */
    @Override
    public CustomerContract selectContractById(String contractId) {
        CustomerContract customerContract = customerContractMapper.selectByPrimaryKey(contractId);
        return customerContract;
    }

    @Override
    public CustomerContract selectContractByContractNumber(String contractNumber) {
        CustomerContractExample customerContractExample = new CustomerContractExample();
        CustomerContractExample.Criteria criteria = customerContractExample.createCriteria();
        criteria.andContractNumberEqualTo(contractNumber);
        List<CustomerContract> customerContractList = customerContractMapper.selectByExample(customerContractExample);
        if(customerContractList.size()>0){
            return customerContractList.get(0);
        }else {
            return null;
        }
    }

    /***
     * @Description:查询未回款合同
     * @Author: luojie
     * @Date: 2021/4/26 9:49
     */
    @Override
    public List<CustomerContract> selectUnpaidContract() {
        UserAccount userAccount = (UserAccount)SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        CustomerContractExample customerContractExample = new CustomerContractExample();
        customerContractExample.setOrderByClause("create_tm desc");
        CustomerContractExample.Criteria criteria = customerContractExample.createCriteria();
        criteria.andCreatePeopleIdEqualTo(userAccount.getAccountId());
        criteria.andDeleteStatusEqualTo(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        //查询未回款的数据
        criteria.andPaymentStatusEqualTo("0");
        List<CustomerContract> customerContractList = customerContractMapper.selectByExample(customerContractExample);
        return customerContractList;
    }

    /**
     * 根据会员id查询会员的开始时间和结束时间
     * @param customerId
     * @return
     */
    @Override
    public CustomerContractVO getCustomerVipDateByCustomerId(String customerId) {
        return contractCustomMapper.getCustomerVipDateByCustomerId(customerId);
    }

    /**
     * 商机详情-查询商机客户下面未过期的合同
     * @param customerId 客户id
     * @return
     */
    @Override
    public List<CustomerContractVO> selectByCustomerId(String customerId) {
        List<CustomerContractVO> customerContractList = contractCustomMapper.selectByCustomerId(customerId);
        return customerContractList;
    }


    /**
     * @Description: 通过合同编号获取数据
     * @Param: [contractNum]
     * @Return: java.util.List<com.crm.model.vo.datasearch.DataSearchResultVO>
     * @Author: lixq-f
     * @Date: 2021/5/13
     **/
    @Override
    public List<DataSearchResultVO> selectDataByContractNum(String contractNum) {
        return contractCustomMapper.selectDataByContractNum(contractNum);
    }

    /**
     * 更新合同全部字段
     * @param contract
     */
    @Override
    public void updateByPrimaryKey(CustomerContract contract) {
        customerContractMapper.updateByPrimaryKey(contract);
    }



    /**
     * @Description: 查询单品合同列表
     * @Param: [customerContractQO, orderStr]
     * @Return: java.util.List<com.crm.model.vo.customerContractManager.CustomerContractVO>
     * @Author: lixq-f
     * @Date: 2021/6/17
     **/
    @Override
    public List<CustomerContractVO> selectSingleContractList(CustomerContractQO customerContractQO,
                                                             String orderStr) {
        return contractCustomMapper.selectSingleContractList(customerContractQO, orderStr);
    }

    /**
     * 通过联系人id查询合同信息
     * @param contactId 联系人id
     * @return
     */
    @Override
    public List<CustomerContract> selectByContactId(String contactId) {
        CustomerContractExample customerContractExample = new CustomerContractExample();
        CustomerContractExample.Criteria criteria = customerContractExample.createCriteria();
        criteria.andContactIdEqualTo(contactId);
        List<CustomerContract> customerContractList = customerContractMapper.selectByExample(customerContractExample);
        return customerContractList;
    }

    /***
     * @Description:全局更新合同字段
     * @Param:
     * @Author: luojie
     * @Date: 2021/8/3 11:22
     */
    @Override
    public Boolean updateCustomerContractWithAllModel(CustomerContract customerContract) {
        int num = customerContractMapper.updateByPrimaryKey(customerContract);
        return num > 0;
    }

    /**
     * 通过订单id查询合同信息
     * @param productOrderId 订单id
     * @return
     */
    @Override
    public CustomerContract selectContractByOrderId(String productOrderId) {
        CustomerContractExample customerContractExample = new CustomerContractExample();
        CustomerContractExample.Criteria criteria = customerContractExample.createCriteria();
        criteria.andOrderIdEqualTo(productOrderId);
        List<CustomerContract> list = customerContractMapper.selectByExample(customerContractExample);
        if(list != null && list.size() > 0){
            return list.get(0);
        }else{
            return null;
        }
    }

    /**
     * (客服部)-》客户列表-》查看-》合同&订单-》编辑合同详情
     * @param contractId --合同ID
     * @author yincuimei
     * @return
     */
    @Override
    public ContractDetailVO selectContractDetailVOById(String contractId) {
        return contractCustomMapper.selectContractDetailVO(contractId);
    }

    /**
     * 根据客户id查询合同列表
     * @param customerId
     * @return
     */
    @Override
    public List<ContractContactVO> selectContractContactByCustomerId(String customerId, String order, List<Integer> auditStatusList, List<Integer> onTheJobSituationList) {
        List<ContractContactVO> contractContactVOList =  contractCustomMapper.selectContractContactByCustomerId(customerId,order, auditStatusList,onTheJobSituationList);
        return contractContactVOList;
    }

    /**
     * (客服部)-编辑客户时查询合同表生效中合同的开始日期及结束日期
     * @param customerId --客户ID
     * @author yincuiemi
     * @return
     */
    @Override
    public List<Map<String, Date>> selectCustomerContractByCustomerId(String customerId) {
        return contractCustomMapper.selectCustomerContractByCustomerId(customerId);
    }

    /**
     * 批量补充合同表客户信息(临时用补充正式库数据:customer_id;customer_name为空的)
     * @param customerContractList
     * @author yincuimei
     * @Date(2021-9-26)
     * @return
     */
    @Override
    public Boolean batchUpdateCustomerContractByIds(List<CustomerContract> customerContractList) {
        return contractCustomMapper.batchUpdateCustomerContractByIds(customerContractList) > 0;
    }

    @Override
    public List<ContractLastThreeMonthVO> selectLastThreeMonthsContractList(String accountId) {
        return contractCustomMapper.selectLastThreeMonthsContractList(accountId);
    }

    @Override
    public int updateArriveTimeAndOtherSelectiveInfo(CustomerContract customerContract) {
        return contractCustomMapper.updateArriveTimeAndOtherSelectiveInfo(customerContract);
    }

    @Override
    public List<Map<String, String>> statisticalVipContractCount(char[] contractTypeArr) {
        return contractCustomMapper.statisticalVipContractCount(contractTypeArr);
    }

    @Override
    public List<Map<String, Object>> statisticalVipContractCountAll(char[] contractTypeArr) {
        return contractCustomMapper.statisticalVipContractCountAll(contractTypeArr);
    }


    @Override
    public RepaymentAbility getRepaymentAbility(String dateStr ,String accountId) {
        return contractCustomMapper.getRepaymentAbility(dateStr,accountId);
    }

    /**
     * 客户详情查询合同列表
     * @param customerId 客户id
     * @param accountId 用户id
     * @return
     */
    @Override
    public List<CustomerContractVO> selectContractByCustomerId(String customerId, String accountId,String createId) {
        return contractCustomMapper.selectContractByCustomerId(customerId,accountId,createId);
    }

    /**
     * 通过商机id查询
     * @param opportunityId
     * @return
     */
    @Override
    public CustomerContract selectByOpportunityId(String opportunityId) {
        CustomerContractExample customerContractExample = new CustomerContractExample();
        CustomerContractExample.Criteria criteria = customerContractExample.createCriteria();
        customerContractExample.setOrderByClause("create_tm desc");
        criteria.andOpportunityIdEqualTo(opportunityId);
        criteria.andContractStatusNotEqualTo("4");
        criteria.andDeleteStatusEqualTo(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        List<CustomerContract> list = customerContractMapper.selectByExample(customerContractExample);
        if(list != null && list.size() > 0){
            return list.get(0);
        }else{
            return null;
        }
    }


    /**
     * 客服首页-合同未审核数量
     * @Author renshaorong
     * @Date 2021/12/16
     * @return
     */
    @Override
    public Integer getCustomerContractNum() {
        return contractCustomMapper.getCustomerContractNum();
    }

    /**
     * 创建会员统计
     * @param year
     * @return
     */
    @Override
    public List<Map<String, Object>> getContractNumByCreate(Integer year) {
        return contractCustomMapper.getContractNumByCreate(year);
    }


    /**
     * 通过/未通过会员统计
     * @param year
     * @return
     */
    @Override
    public List<Map<String, Object>> getContractNumByPass(Integer year, Integer pathStatus) {
        return contractCustomMapper.getContractNumByPass(year,pathStatus);
    }

    /**
     * 生效会员统计
     * @param year
     * @return
     */
    @Override
    public List<Map<String, Object>> getContractNumByEffect(@Param("year") Integer year){
        return contractCustomMapper.getContractNumByEffect(year);
    }
}
